import KoaRouter from 'koa-router'
import Config from '@/config/Config'
import verifyToken from '@/middlewares/verifyToken'
import { Models } from '@/common/typings/modle'
import { command } from '@/server/mysql'
import { Success } from '@/core/HttpException'
const router = new KoaRouter({
  prefix: `${Config.API_PREFIX}v1/system/resource`,
})
router.post('/changeTree', verifyToken, async (ctx: Models.Ctx) => {
  const { changeList } = ctx.request.body as any
  console.log('changeList:', changeList)
  const result = (
    await command(
      changeList
        .map(
          (item: any) =>
            `UPDATE system_resource SET ${
              item.sortNumber === 0 || !!item.sortNumber
                ? `sort_number = '${item.sortNumber}'${item.parentUniqueProp !== undefined ? ',' : ''}`
                : ``
            } ${
              item.parentUniqueProp !== undefined
                ? `parent_unique_prop = ${
                    typeof item.parentUniqueProp === 'string' ? `'${item.parentUniqueProp}'` : `NULL`
                  }`
                : ``
            } WHERE id = '${item.id}';`,
        )
        .join(''),
      true,
    )
  ).results
  // const result = { affectedRows: 1 }
  // console.log('result:', result)
  if (
    Array.isArray(result)
      ? result.filter((item) => item.affectedRows === 1).length === changeList.length
      : result.affectedRows === 1
  ) {
    throw new Success({ data: result, msg: '修改成功' })
  }
})
export default router
